<template>
  <div class="bottom-view">
    <el-card class="view">
      <template #header>关键词搜索</template>
      <div class="content">
        <div class="chart-wrap">
          <div class="chart">
            <div class="title">搜索用户数</div>
            <div class="count">{{lineCartData.totalUser | numberFormat}}</div>
            <!-- <div class="echarts">图表</div> -->
            <v-chart :option="getOption('userList', '搜索用户数')"></v-chart>
          </div>
          <div class="chart">
            <div class="title">搜索量</div>
            <div class="count">{{lineCartData.totalCount | numberFormat}}</div>
            <v-chart :option="getOption('countList', '搜索量')"></v-chart>
          </div>
        </div>

        <el-table :data="tableData" style="width: 100%">
          <el-table-column prop="no" label="排名" />
          <el-table-column prop="word" label="关键字" />
          <el-table-column prop="count" label="搜索量" />
          <el-table-column prop="user" label="搜索用户数" />
          <el-table-column prop="percent" label="搜索占比" />
        </el-table>

        <el-pagination
          layout="prev, pager, next"
          :total="totalTableData.length"
          :current-page.sync="currentpage"
          :page-size="pageSize"
        ></el-pagination>
      </div>
    </el-card>
    <el-card class="view">
      <template #header>
        <span>分类销售排行</span>
        <el-radio-group v-model="radioSelect" size="small">
          <el-radio-button label="品类"></el-radio-button>
          <el-radio-button label="商品"></el-radio-button>
        </el-radio-group>
      </template>
      <div class="content">
        <v-chart :option="getPieOption()" />
      </div>
    </el-card>
  </div>
</template>

<script>
import { mapState } from "vuex";
export default {
  name: "BottomView",

  data() {
    return {
      radioSelect: "商品",
      currentpage: 1,
      pageSize: 5
    };
  },

  /* 
  "searchWord": [
    {
    "word": "北京",
    "count": 3440,
    "user": 1626
  }]
  "saleRank": {
      "category": {
        "axisX": ["粉面粥店", "简餐便当", "汉堡披萨", "香锅冒菜", "小吃炸串", "地方菜系", "轻食简餐"],
        "data1": [56, 52, 95, 41, 30, 69, 63]
      },
      "goods": {
        "axisX": ["草莓", "甘蔗", "榴莲", "菠萝", "香蕉", "梨", "苹果"],
        "data1": [68, 15, 41, 56, 70, 25, 31]
      }
    }

    const {category: {axisX, data1}, goods: {axisX: axisX2, data1: data2}} = this.saleRank
  */
  computed: {
    ...mapState({
      searchWord: state => state.data.reportData.searchWord || [],
      saleRank: state => state.data.reportData.saleRank
    }),


    /* 
    根据saleRank来计算出饼图显示所需要的所有数据
    categoryList: 
      ​	categoryList.total = 400
      ​	{
      ​		name:  粉面粥店|13.79%
      ​		value: 56,
      ​		labelName:  粉面粥店
      ​		percent: 13.79%
      ​	}
    productList
    */
    pieChartData () {
      const data = {
        categoryList: [],
        productList: [],
      }

      if (this.saleRank) {
        const {category: {axisX, data1}, goods: {axisX: axisX2, data1: data2}} = this.saleRank
        /* 
        "axisX": ["粉面粥店", "简餐便当", "汉堡披萨", "香锅冒菜", "小吃炸串", "地方菜系", "轻食简餐"],
        "data1": [56, 52, 95, 41, 30, 69, 63]
        {
      ​		name:  粉面粥店|13.79%
      ​		value: 56,
      ​		labelName:  粉面粥店
      ​		percent: 13.79%
      ​	}
        */
        // 计算分类总数量
        const total = data1.reduce((pre, item) => pre + item, 0)
        data.categoryList.total = total
        // 向categoryList中添加包含name/value/labelName/percent的对象
        data1.forEach((value, index) => {
          const percent = (value / total * 100).toFixed(2) + '%'
          data.categoryList.push({
            name: axisX[index] + '|' + percent,
            value,
            labelName: axisX[index],
            percent,
          })
        })


        // 计算商品总数量
        const total2 = data2.reduce((pre, item) => pre + item, 0)
        data.productList.total = total2

        // 向productList中添加包含name/value/labelName/percent的对象
        data2.forEach((value, index) => {
          const percent = (value / total2 * 100).toFixed(2) + '%'
          data.productList.push({
            name: axisX2[index] + '|' + percent,
            value,
            labelName: axisX2[index],
            percent,
          })
        })
      }

      return data
    },

    /* 
    根据searchWord计算出图表显示所需要的所有数据
    关键字的数组: wordList: xAxiosData
    搜索量的数组: countList  右侧的series的data
    搜索用户量的数组: userList   左侧的Series的data
    搜索量的总数: totalCount
    搜索用户量的总数: totalUser
    "searchWord": [
      {
      "word": "北京",
      "count": 3440,
      "user": 1626
    }]
    */
    lineCartData() {
      const data = {
        wordList: [],
        countList: [],
        userList: [],
        totalCount: 0,
        totalUser: 0
      };

      this.searchWord.forEach(item => {
        data.wordList.push(item.word);
        data.countList.push(item.count);
        data.userList.push(item.user);
        data.totalCount += item.count;
        data.totalUser += item.user;
      });

      return data;
    },

    /* 
    table列表总数据
    "searchWord": [
      {
      "word": "北京",
      "count": 3440,
      "user": 1626
    }]
    */
    totalTableData() {
      const { searchWord } = this;
      // 产生一个排序后的数组(根据count降序)
      const arr = [...searchWord].sort(
        (item1, item2) => item2.count - item1.count
      );
      // 给每个元素对象添加2个属性: no, percent
      return arr.map((item, index) => ({
        ...item,
        no: index + 1,
        percent: ((item.user / item.count) * 100).toFixed(2) + "%"
      }));
    },

    /* 
    计算当前页的列表数据
    */
    tableData() {
      const { totalTableData, currentpage, pageSize } = this;
      // 1     0 5
      // 2     5  10
      // 3     10 15
      return totalTableData.slice(
        (currentpage - 1) * pageSize,
        currentpage * pageSize
      );
    }
  },

  methods: {
    getOption(listName, name) {
      return {
        xAxis: {
          boundaryGap: false,
          show: false,
          data: this.lineCartData.wordList
        },
        yAxis: {
          show: false
        },
        series: {
          name,
          type: "line",
          data: this.lineCartData[listName],
          smooth: true,
          areaStyle: {
            color: "#D8EEFF"
          },
          lineStyle: {
            color: "#5FBBFF"
          },
          itemStyle: {
            opacity: 0
          }
        },
        tooltip: {
          trigger: "axis"
        },

        grid: {
          left: 0,
          top: 0,
          right: 0,
          bottom: 0
        }
      };
    },

    getPieOption() {
      const text = this.radioSelect + '分布'
      const {productList, categoryList} = this.pieChartData
      const list = this.radioSelect==='商品' ? productList : categoryList
      return {
        title: [
          {
            text,
            textStyle: {
              fontSize: 14
            }
          },

          {
            text: '累计订单量',
            textStyle: {
              fontSize: 14,
              color: '#666'
            },
            subtext: list.total,
            subtextStyle: {
              fontSize: 30,
              color: '#000'
            },

            left: '34%',
            top: '44%',
            textAlign: 'center'
          }
        ],

        tooltip: {
          trigger: "item",
          formatter (params) { // 自定义提示框内容
            // console.log(params)
            const {seriesName, marker, data: {labelName, value, percent}} = params
            return `
              ${seriesName}<br/>
              ${marker} ${labelName}<br/>
              ${marker} ${value}<br/>
              ${marker} ${percent}
            `
          }
        },


        legend: {
          orient: 'vertical',
          top: "middle",
          left: "70%"
        },

        series: [
          {
            name: text,
            type: "pie",
            radius: ["35%", "50%"],
            center: ['35%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderColor: "#fff",
              borderWidth: 2
            },
            label: {
              show: true,
              formatter (params) { // 指定显示labelName
                return params.data.labelName
              }
            },
            labelLine: {
              show: true,
              length: 5,
              length2: 5,
              smooth: true
            },
            data: list
          }
        ]
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.bottom-view {
  display: flex;
  margin-top: 20px;
  .view {
    flex: 1;
    &:first-child {
      margin-right: 10px;
    }
    &:last-child {
      margin-left: 10px;
    }

    ::v-deep.el-card__header {
      height: 60px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .content {
      height: 450px;
      .chart-wrap {
        display: flex;
        .chart {
          flex: 1;
          &:first-child {
            margin-right: 5px;
          }
          &:last-child {
            margin-left: 5px;
          }

          .title {
            font-size: 12px;
            color: #666;
          }
          .count {
            font-size: 25px;
            letter-spacing: 1px;
          }
          .echarts {
            height: 50px;
          }
        }
      }

      .el-pagination {
        margin-top: 10px;
        text-align: right;
      }
    }
  }
}
</style>
